import { AddressService } from './../../../../../services/address.service';
import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core';
import { NzCascaderOption } from 'ng-zorro-antd/cascader';
import { NzMessageService } from 'ng-zorro-antd/message';
import { codeList } from 'src/app/models';
import { BaseFieldComponent } from '../base-field/base-field.component';
import { BaseService, DataRegisterService } from 'src/app/services';
import { EventManagerService } from 'src/app/services/event-manager.service';
import { OrganizationService } from 'src/app/services/organization.service';
import { UploadService } from 'src/app/services/upload.service';
import { EngineService } from '../../../services/engine.service';
import { PermitConfig } from '../../../models';

@Component({
  selector: 'zepride-address-select',
  templateUrl: './address-select.component.html',
  styleUrls: ['./address-select.component.less', '../field.common.less']
})
export class AddressSelectComponent extends BaseFieldComponent implements OnInit, AfterViewInit, OnDestroy {

  dataMode = [];
  nzOptions: NzCascaderOption[] = codeList.concat();
  values: string[] = [];

  provinceList = [];
  cityList = [];
  areaList = [];

  curProvince;
  curCity;
  curArea;

  readonlyValue: string;

  permitConfig: PermitConfig[] = [
    { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
    { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' }
  ];

  constructor(
    protected engineService: EngineService,
    protected baseSvr: BaseService,
    protected eventSvr: EventManagerService,
    protected orgSvr: OrganizationService,
    public uploadService: UploadService,
    protected msg: NzMessageService,
    public addSvr: AddressService,
    protected dataRegisterService: DataRegisterService
  ) {
    super(engineService, baseSvr, eventSvr, orgSvr, uploadService, msg, dataRegisterService);
  }

  ngOnInit() {
    this.provinceList = this.addSvr.getProvince();
    if (this.bindData && typeof (this.bindData) === 'string') {
      const addNameList = this.bindData.split(',');
      this.curProvince = this.getKeyValue({ name: addNameList[0] }, this.provinceList);
      this.provinceChange();
      this.curCity = this.getKeyValue({ name: addNameList[1] }, this.cityList);
      this.cityChange();
      this.curArea = this.getKeyValue({ name: addNameList[2] }, this.areaList);

      this.dataModel[this.componentData.bindField] = `${this.curProvince.name},${this.curCity.name}${this.curArea ? ',' + this.curArea.name : ''}`;
    }
    else {
      if (this.componentData.defaultValue) {
        this.curProvince = this.getKeyValue(this.componentData.defaultValue.province, this.provinceList);
        this.provinceChange();
        if (this.componentData.defaultValue.city) {
          this.curCity = this.getKeyValue(this.componentData.defaultValue.city, this.cityList);
          this.cityChange(this.curArea);
          this.curArea = this.getKeyValue(this.componentData.defaultValue.area, this.areaList);
        }
        this.setBindData(this.dataMode.map(x => {
          return {
            name: x
          };
        }));
      }
    }

    if (this.curProvince) {
      this.readonlyValue = `${this.curProvince.name}-${this.curCity.name}${this.curArea ? '-' + this.curArea.name : ''}`;
    }

  }

  ngAfterViewInit() {
    setTimeout(() => {
      this.setAuthorityData();
    }, 0);

    this.registerModelChange();
  }

  private getKeyValue(item: { name: any; }, list: any[]) {
    if (list) {
      return list.find(x => x.name === item.name);
    }
    else {
      return null;
    }
  }

  provinceChange(city?) {
    this.cityList = this.curProvince ? this.curProvince.children : null;
    if (this.cityList) {
      if (!city) {
        this.curCity = this.cityList[0];
      }

      if (!this.cityList.find(x => x.name === '省本级')) {
        this.cityList.push({
          code: '-1',
          name: '省本级'
        });
      }
    } else {
      this.curCity = null;
    }

    this.cityChange();

    this.setBindData();
  }

  cityChange(item?) {
    this.areaList = this.curCity ? this.curCity.children : null;
    if (this.areaList) {
      if (!item) {
        this.curArea = this.areaList[0];
      }
      if (!this.areaList.find(x => x.name === '市本级')) {
        this.areaList.push({
          code: '-1',
          name: '市本级'
        });
      }
    } else {
      this.curArea = null;
    }

    this.setBindData();
  }

  registerModelChange() {
    this.modelChange$ = this.engineService.dataModelChange$.subscribe(data => {
      if (data.identifyId !== this.componentData.identifyId && data.bindField === this.componentData.bindField) {
        this.dataMode = data.value;
      }
    });
  }

  /**
   * 设置绑定字段的值
   * @param value 新的值
   */
  setBindData(value?: any[]) {
    const newValue = [
      this.curProvince,
      this.curCity,
      this.curArea
    ];

    const pName = this.curProvince ? this.curProvince.name : '';
    const cName = this.curCity ? this.curCity.name : '';
    const aName = this.curArea ? this.curArea.name : '';

    const bindField = this.componentData.bindField;
    if (bindField) {
      this.dataModel[bindField] = [pName, cName, aName].filter(x => x).join(',');
      this.engineService.dataModelChange$.next({
        bindField,
        value: newValue,
        identifyId: this.componentData.identifyId,
        tmpComItemId: this.tmpComItemId,
        selector: this.componentData.selector,
        dataModel: this.dataModel
      });
    } else {
      this.componentData.defaultValue = newValue;
    }
    // this.validate();
  }

  ngOnDestroy() {
    if (this.modelChange$) {
      this.modelChange$.unsubscribe();
    }
  }
}
